<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="queryForm" :inline="true" :model="queryParams" size="small">
        <el-form-item prop="params.type">
          <el-input
            v-model="queryParams.params.name"
            class="filter-item"
            clearable
            placeholder="商品名称"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.type">
          <el-select v-model="queryParams.params.type" clearable placeholder="商品分类">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item prop="params.barcode">
          <el-input
            v-model="queryParams.params.barcode"
            class="filter-item"
            clearable
            placeholder="商品条码"
            style="width: 150px;"
          />
        </el-form-item>
        <el-form-item prop="params.customCode">
          <el-input
            v-model="queryParams.params.customCode"
            class="filter-item"
            clearable
            placeholder="商品自编码"
            style="width: 150px;"
          />
        </el-form-item>
        <!-- 按钮 -->
        <el-button
          v-permission="['/store/commodity/search']"
          v-waves
          class="filter-item"
          icon="el-icon-search"
          size="small"
          style="margin-left: 10px;"
          type="primary"
          @click="getDataList"
        >查询
        </el-button>
        <el-button
          v-permission="['/store/commodity/add']"
          v-waves
          class="filter-item"
          icon="el-icon-plus"
          size="small"
          type="primary"
          @click="handleOpenDialog('add')"
        >新增
        </el-button>
        <el-button
          v-permission="['/store/commodity/search']"
          v-waves
          class="filter-item"
          icon="el-icon-refresh"
          size="small"
          type="primary"
          @click="resetQueryForm"
        >重置
        </el-button>
      </el-form>
    </div>
    <!-- 数据表格 -->
    <el-table
      v-loading="dataListLoading"
      :data="dataList"
      border
      fit
      highlight-current-row
      size="small"
      style="width: 100%;"
      @sort-change="handleSortChange"
    >
      <el-table-column :index="shownIndex" align="center" fixed label="序号" type="index" />
      <el-table-column align="center" label="商品名称" prop="name" show-overflow-tooltip />
      <el-table-column align="center" label="图片" prop="picUrls">
        <template slot-scope="scope">
          <el-image
            :preview-src-list="scope.row.picUrls ? scope.row.picUrls.split(',') : []"
            :src="scope.row.picUrls ? scope.row.picUrls.split(',')[0] : ''"
            fit="fill"
            style="width: 60px;height: 60px"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="商品分类" prop="typeName" show-overflow-tooltip />
      <el-table-column align="center" label="商品类型" prop="categoryName" show-overflow-tooltip />
      <el-table-column align="center" label="商品条码" prop="barcode" show-overflow-tooltip />
      <el-table-column align="center" label="自编码" prop="customCode" show-overflow-tooltip />
      <el-table-column align="center" label="商品规格" prop="spec" show-overflow-tooltip />
      <el-table-column align="center" label="计量单位" prop="unitName" show-overflow-tooltip />
      <el-table-column align="center" label="成本价" prop="costPrice" show-overflow-tooltip />
      <el-table-column align="center" label="销售价" prop="salePrice" show-overflow-tooltip />
      <el-table-column align="center" label="创建人" prop="creatorName" show-overflow-tooltip />
      <el-table-column align="center" label="创建时间" prop="createdDate" show-overflow-tooltip />
      <el-table-column align="center" label="编辑人" prop="modifierName" show-overflow-tooltip />
      <el-table-column align="center" label="编辑时间" prop="modifiedDate" show-overflow-tooltip />
      <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="250">
        <template slot-scope="scope">
          <el-button
            v-permission="['/store/commodity/search']"
            v-waves
            size="mini"
            type="info"
            @click="handleOpenDialog('view', scope.row)"
          >查看
          </el-button>
          <el-button
            v-permission="['/store/commodity/update']"
            v-waves
            size="mini"
            type="primary"
            @click="handleOpenDialog('update', scope.row)"
          >编辑
          </el-button>
          <el-button
            v-permission="['/store/commodity/delete']"
            v-waves
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.size"
        :page-sizes="[10,20,30, 50]"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 新增-编辑对话框 -->
    <el-dialog
      v-loading="dialogLoading"
      :close-on-click-modal="false"
      :title="dialogTitleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      element-loading-text="保存中"
    >
      <el-form
        id="dataForm"
        ref="dataForm"
        :model="dataForm"
        :rules="rules"
        size="small"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="商品名称：" prop="name">
              <el-input v-model="dataForm.name" :readonly="formReadOnly" placeholder="商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品分类" prop="type">
              <el-select v-model="dataForm.type" :disabled="formReadOnly" placeholder="请选择" style="width: 100%">
                <el-option
                  v-for="item in typeList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品条码：" prop="barcode">
              <el-input v-model="dataForm.barcode" :readonly="formReadOnly" placeholder="商品条码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="自编码：" prop="customCode">
              <el-input v-model="dataForm.customCode" :readonly="formReadOnly" placeholder="自编码" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品类型：" prop="category">
              <el-select
                v-model="dataForm.category"
                :disabled="formReadOnly"
                clearable
                placeholder="商品分类"
                style="width: 100%"
              >
                <el-option
                  v-for="item in categoryList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="商品规格：" prop="spec">
              <el-input v-model="dataForm.spec" :readonly="formReadOnly" placeholder="商品规格" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="计量单位：" prop="unit">
              <el-select
                v-model="dataForm.unit"
                :disabled="formReadOnly"
                clearable
                placeholder="商品单位"
                style="width: 100%"
              >
                <el-option
                  v-for="item in unitList"
                  :key="item.id"
                  :label="item.value"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="成本价：" prop="costPrice">
              <el-input v-model="dataForm.costPrice" :readonly="formReadOnly" placeholder="成本价" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="销售价：" prop="salePrice">
              <el-input v-model="dataForm.salePrice" :readonly="formReadOnly" placeholder="销售价" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input v-model="dataForm.remark" :readonly="formReadOnly" autosize placeholder="备注" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider><i class="el-icon-picture" /> 图片信息</el-divider>

      <!-- 显示当前已有的图片 -->
      <div class="image-container">
        <el-row :gutter="20">
          <el-col v-for="url in dataForm.picUrls ? dataForm.picUrls.split(',') : []" :key="url" :md="4">
            <div class="image-item">
              <el-image
                :preview-src-list="dataForm.picUrls ? dataForm.picUrls.split(',') : []"
                :src="url"
                fit="fit"
                style="width: 120px; height: 120px"
              />
              <div class="del-btn">
                <el-button circle icon="el-icon-delete" size="mini" type="danger" @click="handleDelPicture(url)" />
              </div>
            </div>
          </el-col>
          <el-col :md="8">
            <el-upload
              :auto-upload="false"
              :file-list="fileList"
              :on-change="handlePicChange"
              :on-remove="handleRemove"
              accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
              action="#"
              multiple
            >
              <el-button slot="trigger" size="small" type="primary">选取图片</el-button>
              <el-button size="small" style="margin-left: 10px;" type="success" @click="submitUpload">上传图片</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-col>
        </el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='add'" size="small" type="primary" @click="handleAdd">确定</el-button>
        <el-button v-if="dialogStatus==='update'" size="small" type="primary" @click="handleUpdate">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { add, del, fetchList, update } from '@/api/store/commodity'
import { findByObject } from '@/api/store/category'
import { typeList } from '@/api/system/dict'
import { upload } from '@/api/system/file'

export default {
  name: 'Commodity',
  data() {
    return {
      total: 0,
      dataList: [],
      typeList: [],
      unitList: [],
      categoryList: [],
      fileList: [],
      dataListLoading: true,
      dialogFormVisible: false,
      dialogStatus: '',
      dialogLoading: false,
      dialogTitleMap: {
        add: '新增',
        update: '编辑'
      },
      // 查询参数对象
      queryParams: {
        page: 1,
        size: 10,
        params: {
          name: '',
          type: '',
          barcode: '',
          customCode: ''
        }
      },
      dataForm: {
        name: '',
        type: '',
        category: '',
        barcode: '',
        customCode: '',
        spec: '',
        unit: '',
        costPrice: '',
        salePrice: '',
        picUrls: '',
        remark: ''
      },
      rules: {
        name: [{ required: true, message: '商品名称不能为空', trigger: 'change' }],
        barcode: [{ required: true, message: '商品条码不能为空', trigger: 'change' }],
        customCode: [{ required: true, message: '商品自编码不能为空', trigger: 'change' }],
        type: [{ required: true, message: '商品类别不能为空', trigger: 'change' }],
        costPrice: [{ required: true, message: '商品成本价不能为空', trigger: 'change' }],
        salePrice: [{ required: true, message: '商品销售价不能为空', trigger: 'change' }]
      }
    }
  },
  computed: {
    formReadOnly() {
      return this.dialogStatus === 'view'
    }
  },
  mounted() {
    this.getDataList()
    findByObject({}).then(res => {
      this.typeList = res.data
    })
    typeList({ type: 'category' }).then(res => {
      this.categoryList = res.data
    })
    typeList({ type: 'unit' }).then(res => {
      this.unitList = res.data
    })
  },
  methods: {
    shownIndex(index) {
      return (this.queryParams.page - 1) * this.queryParams.size + index + 1
    },
    handleSortChange(data) {
      console.log('handleSortChange')
      console.log(data)
      if (data.order) {
        if (data.order.indexOf('asc') > -1) {
          this.queryParams.sortOrder = 'asc'
        } else {
          this.queryParams.sortOrder = 'desc'
        }
        this.queryParams.sortName = data.prop
      }
      console.log(this.queryParams)
    },
    // 手动重置表单
    resetDataForm() {
      if (this.$refs['dataForm']) {
        // 由于编辑数据的时候会导致表单对象的初始化值发生变更，所以在重置表单前先手动重置表单对象的值
        this.dataForm = {
          name: '',
          type: '',
          category: '',
          barcode: '',
          customCode: '',
          spec: '',
          unit: '',
          costPrice: '',
          salePrice: ''
        }
        this.$refs['dataForm'].resetFields()
      }
    },
    resetQueryForm() {
      this.$refs['queryForm'].resetFields()
      this.queryParams.page = 1
      this.getDataList()
    },
    getDataList() {
      this.dataListLoading = true
      fetchList(this.queryParams)
        .then(res => {
          console.log(res)
          this.dataList = res.data.records
          this.total = res.data.total
          this.dataListLoading = false
          this.$message.success(res.msg || '获取数据成功')
        })
        .catch(err => {
          console.log(err)
          this.dataListLoading = false
        })
    },
    handleSizeChange(size) {
      this.queryParams.size = size
      this.getDataList()
    },
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.getDataList()
    },
    handleOpenDialog(type, rowData) {
      // 表单状态为新增/编辑、打开新增/编辑窗口
      this.resetDataForm()
      this.dialogStatus = type
      this.dialogFormVisible = true
      if (type === 'update' || type === 'view') {
        this.dataForm = JSON.parse(JSON.stringify(rowData))
      }
    },
    handleAdd() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          add(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '新增成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleUpdate() {
      // 先进行表单校验
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dialogLoading = true
          update(this.dataForm)
            .then(res => {
              console.log(res)
              this.$message.success(res.msg || '修改成功')
              this.dialogLoading = false
              this.dialogFormVisible = false
              this.resetDataForm()
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
              this.dialogLoading = false
            })
        }
      })
    },
    handleDelete(rowData) {
      this.$confirm('是否删除该记录？', '删除提示', { type: 'warning' })
        .then(() => {
          del(rowData.id)
            .then(res => {
              console.log(res)
              // this.$message.success(res.msg || '删除成功')
              this.getDataList()
            })
            .catch(err => {
              console.log(err)
            })
        })
        .catch(cancel => {
          console.log(cancel)
        })
    },
    handlePicChange(file, fileList) {
      console.log('handlePicChange')
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      console.log('handleRemove')
      this.fileList = fileList
    },
    handleDelPicture(url) {
      console.log('handleDelPicture')
      this.dataForm.picUrls = this.dataForm.picUrls.split(',').filter(item => item !== url).join(',')
    },
    submitUpload() {
      upload(this.fileList).then(res => {
        const tmpList = this.dataForm.picUrls ? this.dataForm.picUrls.split(',') : []
        for (let i = 0; i < res.data.length; i++) {
          if (tmpList.indexOf(res.data[i].fileUrl) === -1) {
            tmpList.push(res.data[i].fileUrl)
          }
        }
        this.dataForm.picUrls = tmpList.join(',')
      }).catch(err => {
        console.log(err || '图片上传失败')
      })
    }
  }
}
</script>
<style scoped>
</style>
